<?php
/**
 * ContentService.php
 * User: tommy
 */

namespace service\cms;

use Exception;
use lib\qiniu\QiniuLib;
use Svick\Config\Config;

class ContentService
{
    /**
     * 文章内容处理
     *
     * @param $content
     * @param string $old_content
     * @param bool $is_update
     * @return array|string|string[]
     * @throws Exception
     */
    public static function mediaDeal($content, $old_content = '', $is_update = false)
    {
        $medias = ContentService::grab($content, 'tmp');
        foreach ($medias as $media) {
            $key = ContentService::getKey($media, 'tmp');
            QiniuLib::moveTmpFile($key, 'data');
        }

        if ($is_update) {
            $new_medias = ContentService::grab($content, 'cdn');
            $old_medias = ContentService::grab($old_content, 'cdn');
            foreach ($old_medias as $old_media) {
                if (!in_array($old_media, $new_medias)) {
                    $key = ContentService::getKey($old_media, 'data');
                    QiniuLib::deleteFile('data', $key);
                }
            }
        }

        return ContentService::replace($content);
    }

    /**
     * 提取文章中的图片、视频等资源
     *
     * @param $content
     * @param $domain
     * @return array
     */
    public static function grab($content, $domain): array
    {
        //< img src="http://tmp.timegene.cn/1666683255281897384" alt="31bb151edb7.jpg" data-href="" style=""/>
        preg_match_all('@<\s*img\s+src="(http://' . $domain . '.*?)".*?/.*?>@', $content, $matches);
        $srcs = $matches[1];

        //<video poster="c204f86a05af9cf59646e4ea2bd814a5.mp4" controls="true" width="auto" height="auto"><source src="http://tmp.timegene.cn/1666683132461778112" type="video/mp4"/></video>
        preg_match_all('@<video.*?<source\s+src="(http://' . $domain . '.*?)".*?/.*?></video>@', $content, $matches);
        return array_merge($srcs, $matches[1]);
    }

    /**
     * 获取文章简介
     *
     * @param $content
     * @return string
     */
    public static function getIntroduction($content)
    {
        $content = preg_replace([
            '@&nbsp;@',
            '@<\s*img\s+src="(' . Config::runtime('qiniu.resource.data') . '.*?)".*?/>@',
            '@<video.*?<source\s+src="(' . Config::runtime('qiniu.resource.data') . '.*?)".*?/></video>@'
        ], '', $content);
        $content = trim(strip_tags($content));

        return mb_substr($content, 0, 64);
    }

    public static function replace($content)
    {
        return str_replace(Config::runtime('qiniu.resource.tmp'), Config::runtime('qiniu.resource.data') . Config::runtime('qiniu.prefix'), $content);
    }

    public static function getKey($url, $bucket)
    {
        return str_replace(Config::runtime('qiniu.resource.' . $bucket), '', $url);
    }
}
